<?php

namespace API\App\Action;

use Hx\App;
use Hx\Event;
use Hx\Request;

class Category {

    public function __construct() {
        Event::trigger('token-validate');
    }

    public function getAll() {
        $data = App::Model('Category->getAll');
        return !$data ? array('error' => true, 'msg' => '查询失败') : array('category' => $data);
    }

    public function getOne($id) {
        $data = App::Model('Category->getOne', array((int)$id));
        return !$data ? array('error' => true, 'msg' => '查询失败') : array('category' => $data);
    }

    public function addCategory() {
        $data = Request::post(true);
        unset($data['id']);
        unset($data['move']);
        $res = App::Model('Category->addCategory', array($data));
        return $res === false ? array('error' => true, 'msg' => '添加失败') : array(
            'category' => $res
        );
    }

    public function updateCategory($id) {
        $data = Request::post(true);
        if ($id != $data['id']) {
            return array('error' => true, 'msg' => '参数非法');
        }
        unset($data['move']);
        $res = App::Model('Category->updateCategory', array($data));
        return $res === false ? array('error' => true, 'msg' => '修改失败') : array(
            'category' => $res
        );
    }

    public function deleteCategory($id) {
        $move = Request::post('move');
        $res = App::Model('Category->deleteCategory', array($id, $move));
        if ($res === false) {
            return array('error' => true, 'msg' => '移动失败');
        }
        Event::trigger('category-count');
        return array('result' => true);
    }
}